package com.meisupic.copyright.notify;

import com.alibaba.fastjson.JSON;
import com.meisupic.copyright.support.HttpClient;
import com.meisupic.copyright.support.Response;
import java.util.Map;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Author lanjian
 * @Date 2018/4/7 下午9:37
 */
public class NotifyTask implements Runnable, Delayed {

  private static final Logger logger = LoggerFactory.getLogger(NotifyTask.class);

  private long executeTime;

  private Integer notifyTimes;

  private Map<String,String> params;

  private String callBackUrl;

  private NotifyQueue notifyQueue;

  public NotifyTask(long executeTime, Integer notifyTimes,Map<String,String> params,String callBackUrl,NotifyQueue notifyQueue) {
    this.executeTime = executeTime;
    this.notifyTimes = notifyTimes;
    this.callBackUrl = callBackUrl;
    this.notifyQueue = notifyQueue;
    this.params = params;
  }

  @Override
  public long getDelay(TimeUnit unit) {
    return unit.convert(executeTime - System.currentTimeMillis(), TimeUnit.SECONDS);

  }

  @Override
  public int compareTo(Delayed o) {
    NotifyTask task = (NotifyTask) o;
    return executeTime > task.executeTime ? 1 : (executeTime < task.executeTime ? -1 : 0);
  }


  @Override
  public void run() {
    logger.info("回调花瓣参数{}", JSON.toJSONString(params));
    Response response = HttpClient.post(callBackUrl,params);
    logger.info("执行回调通知状态{}结果{}",response.getStatusCode(),response.getContent());
    if(response.getStatusCode()!=200){
      notifyQueue.addElementToList(params,notifyTimes+1,callBackUrl);
    }

  }
}
